using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using NP.Enterprise.Utils.ApiResult;
using System;
using System.Linq;

namespace NP.BPMReportPlatform.Filters
{
    public class ApiResultFilterAttribute : ResultFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(ApiResult.Empty);
                }
                else if (!(objectResult.Value is IApiResult))
                {
                    if (objectResult.DeclaredType is null)
                    {
                        context.Result = new ObjectResult(ApiResult.Failed(JsonConvert.SerializeObject(objectResult.Value), objectResult.StatusCode));
                    }
                    else
                    {
                        var apiResult = Activator.CreateInstance(
                            typeof(ApiResult<>).MakeGenericType(objectResult.DeclaredType), objectResult.Value, objectResult.StatusCode);
                        context.Result = new ObjectResult(apiResult);
                    }
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.HttpContext.Response.StatusCode = 200;
                context.Result = new ObjectResult(ApiResult.Empty);
            }
            else if (context.Result is ContentResult)
            {
                context.HttpContext.Response.StatusCode = 200;
                context.Result = new ObjectResult(ApiResult.Succeed((context.Result as ContentResult).Content));
            }
            else if (context.Result is StatusCodeResult)
            {
                context.HttpContext.Response.StatusCode = 200;
                context.Result = new ObjectResult(ApiResult.From((context.Result as StatusCodeResult).StatusCode));
            }
        }
    }
}